/*
 * ipvn_service.cpp
 *
 *  Created on: Oct 19, 2012
 *      Author: khanhhh
 */

#ifndef IPVN_SERVICE_CPP_
#define IPVN_SERVICE_CPP_
extern "C" {
#include <luajit-2.0/lua.h>
#include <luajit-2.0/lauxlib.h>
#include <luajit-2.0/lualib.h>
}

#include "../lua_interaction/luna.hpp"
#include "ipvn_service.hpp"
#include <iostream>
namespace http {
namespace server3 {

const char ipvn_service::className[] = "ipvn_service";

#define method(class, name) {#name, &class::name}
Luna<ipvn_service>::RegType ipvn_service::methods[] = {
		method(ipvn_service, is_ipvn), { 0, 0 } };
ipvn_service::ipvn_service(lua_State *L) {
	if (lua_gettop(L) >= 2) {
		//std::cout <<"ipvn_constructor"<<std::endl;
		//Tao userdata
		if (lua_isstring(L, 1) && lua_isnumber(L, 2)) {
			this->ip = lua_tostring(L, 1);
			this->port = lua_tointeger(L, 2);
			//start initialize
			//std::cout<<ip<<"\t"<<port<<std::endl;
			socket_ptr_.reset(new apache::thrift::transport::TSocket(ip, port));
			transport_ptr_.reset(new apache::thrift::transport::TBufferedTransport(socket_ptr_));
			protocol_ptr_.reset(new apache::thrift::protocol::TBinaryProtocol(transport_ptr_));
			client_ptr_.reset(new IpvnServiceClient(protocol_ptr_));
			try {
				transport_ptr_->open();
				//std::cout<<"transport_ptr_->open();"<<std::endl;
			} catch (apache::thrift::transport::TTransportException &tx) {
				std::cout
						<< "ERROR: open socket ipvn_service is not successful:"
						<< tx.what() << std::endl;
			}
		}
	}
}
ipvn_service::~ipvn_service() {
	try {
		transport_ptr_->close();
		socket_ptr_->close();
	} catch (apache::thrift::TException &tx) {
		std::cout << "ERROR close transport in ipvn_service:" << tx.what()
				<< std::endl;
	}

}
int ipvn_service::is_ipvn(lua_State *L) {
	std::string region_;
	std::string result_;
	if (lua_isstring(L, 1)) {
		region_ = lua_tostring(L, 1);
		if (transport_ptr_->isOpen()) {
			try {
				//std::cout<<"is_ipvn : "<<region_<<std::endl;
				client_ptr_->isIpvn(result_, region_);
                lua_pushlstring(L,result_.c_str(),result_.length());
                //std::cout<<"result:"<<result_<<std::endl;
                return 1;
			} catch (apache::thrift::TException &tx) {
				std::cout << "ERROR parsing:" << tx.what() << std::endl;
				return 0;
			}
		} else {
			//if not open --> try open again
			try {
				transport_ptr_->open();
				client_ptr_->isIpvn(result_, region_);
                lua_pushlstring(L,result_.c_str(),result_.length());
                return 1;
			} catch (apache::thrift::TException &tx) {
				std::cout << "ERROR open Transport:" << tx.what() << std::endl;
				return 0;
			}
		}
	}
	return 0;
}
}
}
#endif /* IPVN_SERVICE_CPP_ */
